<?php
/**
 * Student Base Controller
 *
 * Student Base Information Management
 * student entry
 *
 * @version $Id: BaseController.php 110 2010-05-16 14:43:41Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package student
 * @subpackage Controller
 */
class Student_BaseController extends Zend_Controller_Action
{
    protected  $_baseForm;

    protected  function _setForm()
    {
        $this->_baseForm = new Student_Form_Student();

        $this->_baseForm->addElement('hidden','year',array(
         'decorators' => $this->_baseForm->noElementDecorator,
          'required'   => true,
          'filters'    => array('StringTrim','StripTags'),
         'size'=>3,
        ))
        ->addElement('hidden','semester',array(
           'decorators' => $this->_baseForm->noElementDecorator,
          'required'   => true,
          'filters'    => array('StringTrim','StripTags'),
         'size'=>3,
        ))
        ->addElement('text','number',array(
          'label'=>'number',
          'required'   => true,
          'filters'    => array('StringTrim','StripTags'),
           'validators' => array('int'),
         'size'=>3,
        ));

    }

    public function indexAction()
    {

        $this->_setForm();
        $system_text = new Default_Model_SystemText();
        $this->view->stud_kind_arr = $system_text->getKindArray('stud_kind');
        $this->view->form = $this->_baseForm;
        if ($this->getRequest()->getParam('year_semester')){
       	    $this->view->year_semester = $this->getRequest()->getParam('year_semester');
       	    $this->view->class_id = $this->getRequest()->getParam('class_id');
       	}
       	else{

       	    $cookie = Zend_Controller_Request_Http::getCookie();
       	    if ( isset($cookie['Student_year_semester'])) {
       	        $this->view->year_semester = $cookie['Student_year_semester'];
       	        $this->view->class_id = $cookie['Student_class_id'];
       	    }else {
       	        $this->view->year_semester = $this->view->Semester['year'].'-'.$this->view->Semester['semester'];
       	        $this->view->class_id = $this->view->lowYear.'-1';
       	    }
       	}

    }

    public function setAction()
    {
        $this->_setForm();
        $request = $this->getRequest();
        if ($request->isPost()){
            if($this->_baseForm->isValid($request->getParams())){
                $data = $this->_baseForm->getValues();
                $updateSn = Teacher_Model_Teacher::getSnById($this->view->user->username);
                $sn = $this->_baseForm->getValue('sn');
                $data['update_sn'] = $updateSn;

                $student =  new Student_Model_Student();
                $student->assignIdentifier($sn);

                $student->fromArray($data);
                $student->save();
                // 學期座號
                $year = $this->_baseForm->getValue('year');
                $semester = $this->_baseForm->getValue('semester');
                $number = $this->_baseForm->getValue('number');
                $studentId = $this->_baseForm->getValue('student_id');
                $q = Doctrine_Query::create()
                ->update('Student_Model_StudentSemester')
                ->set('number','?',$number)
                ->set('student_id','?', $studentId)
                ->where('student_sn=? AND year=? AND semester=?',
                array($sn, $year, $semester)
                );
                $q->execute();

                // 學生身分別

                $arr = array();
                foreach($request->getParam('stud_kind') as $val){
                    $arr[] = (int)$val;
                }
                $str = implode(",",$arr);
                $q = Doctrine_Query::create()
                ->delete("Student_Model_StudentCharacter")
                ->where('student_sn=? ',$sn)
                ->whereNotIn('kind',$str);

                $q->execute();

                //$query = "DELETE FROM student_character WHERE student_sn=$sn AND kind NOT IN($str)";
                //$db->query($query);
                $q = Doctrine_Query::create()
                ->select('kind')
                ->from('Student_Model_StudentCharacter')
                ->where('student_sn=? ',$sn)
                ->whereIn('kind',$str);
                $res = $q->fetchArray();
                //$query = "SELECT kind FROM student_character WHERE student_sn=$sn AND kind  IN($str)";
                //$res = $db->query($query)->fetchAll();
                $data = array();
                foreach ($res as $val) {
                    $data[] = $val;
                }
                $setdata = array_diff($arr,$data);
                foreach ($setdata as $val){
                    $studentCharacter = new Student_Model_StudentCharacter();
                    $studentCharacter->student_sn = $sn;
                    $studentCharacter->kind = $val;
                    $studentCharacter->save();
                }
                $this->_helper->json( $request->getParams());
            }
            else {
                $this->_helper->json(array('error'=>$this->_baseForm->getMessages()));
            }
        }
    }

    /**
     *  upload photo image
     * @return unknown_type
     */
    function uploadphotoAction()
    {

        if($this->_request->isPost()){
            $formData = $this->_request->getPost();
            $student_sn = (int)$this->_request->getParam('student_sn');
            $temp_sn = sprintf("%02X",$student_sn);
            $len = (int) strlen($temp_sn) / 2;
            $path = '';
            for($i=0;$i<$len-1; $i++)
            $path .= substr($temp_sn,$i*2,2).'/';
            $file_path  = $this->_helper->getStorePath('photo/student/'.$path);

            $adapter = new Zend_File_Transfer_Adapter_Http();
            $adapter->setDestination($file_path)
            ->addValidator('Extension',false,'jpeg,jpg,png');
            $photo = $adapter->getFileInfo('photo');
            $temp_arr = explode(".",$photo['photo']['name']);
            $ss = time();

            $file_name =  $ss. '.'.end($temp_arr);
            $photo_name = $ss.'_'.end($temp_arr);
            $adapter->addFilter('Rename', array(
            //$photo['photo']['tmp_name'],
			'target'=>$file_path . $file_name,
			'overwrite'=>true
            ));

            if ($adapter->receive('photo'))
            {
                $student = Doctrine_Core::getTable('Student_Model_Student')
                ->findOneBy('sn',$student_sn);

                //$row = $student-> fetchRow('sn='.$student_sn);
                if ($student->photo_name){
                    $tt = str_replace("_",".",$student->photo_name);
                    if (is_file($file_path.$tt)) {
                        unlink($file_path.$tt);
                        unlink($file_path.'tmb_'.$tt);
                    }
                }
                $student->photo_name = $photo_name;
                $student->save();
                // 縮圖
                $thumb = new Sfs_Image_Thumb($file_path . $file_name);
                $thumb->resize(140);
                $thumb->save($file_path.'tmb_'.$file_name, 100);
                echo $photo_name;
            }
        }
        exit;

    }

    /**
     * 下載照片檔
     *
     */
    public function studentimgAction()
    {

        $ss = $this->_request->getParam('photo');
        $temp = explode("_",$ss);

        $student_sn = (int)$this->_request->getParam('student_sn');
        $temp_sn = sprintf("%02X",$student_sn);
        $len = (int) strlen($temp_sn) / 2 ;
        $path = '';
        for($i=0;$i<$len-1; $i++)
        $path .= substr($temp_sn,$i*2,2).'/';
        $file_path  = $this->_helper->getStorePath('photo/student/'.$path);

        $photo = 'tmb_'.$temp[0].'.'.$temp[1];
//echo $photo,'photo/student/'.$path; exit;
        if (file_exists($file_path.$photo)) {
            $this->_helper->downloadFile($photo,'photo/student/'.$path);
        }

    }

    /**
     * 所有學生資料
     * @return unknown_type
     */
    public function getallAction()
    {
        $year_semester = $this->getRequest()->getParam('year_semester');
        $arr = explode("-",$year_semester);
        $year = (int)$arr[0];
        $semester = (int)$arr[1];
        $classId = $this->getRequest()->getParam('class_id');
        $tempArr = explode("-",$classId);
        $grade = (int)$tempArr[0];
        $classSn = (int)$tempArr[1];

        /*
         $sql = $db->select()
         ->from(array('a'=>'student'))
         ->joinLeft(array('b'=>'student_semester'),
         'a.sn=b.student_sn',array('year','semester','grade','class_sn','number','student_id'))
         ->where('year=?',$year)
         ->where('semester=?',$semester)
         ->where('grade=?',$grade)
         ->where('class_sn=?',$class_sn)
         ->order("b.number");

         $res = $db->fetchAll($sql);
         */
        $q = Doctrine_Core::getTable('Student_Model_Student')
        ->createQuery('a')
        ->select('a.*, b.year AS year, b.semester AS semester, b.grade AS grade,
        b.class_sn AS class_sn,  b.number AS number,  b.student_id AS student_id')
        ->leftJoin('a.Student_Model_StudentSemester b')
        ->where('b.year=? AND b.semester=? AND b.grade=? AND b.class_sn=?',
        array($year,$semester,$grade,$classSn) )
        ->orderBy('b.number');
        $res = $q->fetchArray();
        $arr = array();
        foreach($res as $row)
        $arr[$row['sn']] = $row;

        $q = Doctrine_Query::create()
        ->select ('a.*')
        ->from('Student_Model_StudentCharacter a')
        ->leftJoin('a.Student_Model_StudentSemester b')
        ->where('b.year=? AND b.semester=? AND b.grade=? AND b.class_sn=?',
        array($year,$semester,$grade,$classSn) );

        $res = $q->fetchArray();

        foreach($res as $row)
        $arr[$row['student_sn']]['stud_kind'][] = $row['kind'];


        $this->_helper->json($arr);
    }


    public function getdataAction()
    {
        $sn = (int) $this->getRequest()->getParam('sn',0);
        $year_semester = $this->getRequest()->getParam('year_semester');
        $arr = explode("-",$year_semester);
        $year = (int)$arr[0];
        $semester = (int)$arr[1];
        $arr = array();
        $StudentSemester = Doctrine::getTable('Student_Model_StudentSemester');
        $res  = $StudentSemester->findByDql('year=? AND semester=? AND student_sn=?',
        array($year,$semester,$sn), Doctrine::HYDRATE_ARRAY);
        $arr['semester_data'] = $res;

        $student = Doctrine::getTable('Student_Model_Student');
        $res = $student->findBy('sn',$sn,Doctrine::HYDRATE_ARRAY);
        $arr['student_data'] =  $res;
        /*
         $student_semeser  = new Student_Model_DbTable_StudentSemester();
         $res = $student_semeser->fetchRow("year=$year AND semester=$semester AND student_sn=$sn");
         if ($res)
         $arr['semester_data'] = $res->toArray();

         $student = new Student_Model_DbTable_Student();
         $arr['student_data'] = $student->fetchRow(array('sn=?'=>$sn))->toArray();
         */
        $this->_helper->json($arr);
    }
}

